package pl.hucal.wmkassist;

import pl.hucal.wmkassist.R;
import pl.hucal.wmkassist.network.FacebookConnector;
import pl.hucal.wmkassist.network.LoggingActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class WMKAssistantActivity extends Activity
{
    /** Tag for LogCat */
    private static final String TAG = "WMK_WMKAssistantActivity";
    /** Storage file for internal application data */
    public static final String INTERNAL_PERSIST_NAME = "WMKAssistInternalPersist";
    /** Identifier for Logging-in new activity request */
    private static final int LOGIN_REQUEST = 1;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "In the onCreate() event");

        loadPersistentData();

        // FIXME add second connector
        if (!FacebookConnector.getInstance().isLogged())
        {
            startActivityForResult(new Intent("android.intent.action.LOGGING"), LOGIN_REQUEST);
        }

        setContentView(R.layout.main);
    }

    // FIXME dodac gdzies wczytywanie ustawien
    @Override
    public void onStart()
    {
        super.onStart();
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        Log.d(TAG, "In the onStart() event" + sharedPrefs.getString("units_preference", "buu"));
    }

    @Override
    public void onRestart()
    {
        super.onRestart();
        Log.d(TAG, "In the onRestart() event" + FacebookConnector.getInstance().isLogged());
    }

    @Override
    public void onResume()
    {
        super.onResume();
        Log.d(TAG, "In the onResume() event");
    }

    @Override
    public void onPause()
    {
        super.onPause();
        Log.d(TAG, "In the onPause() event");
        // Save persistent data
        SharedPreferences settings = getSharedPreferences(INTERNAL_PERSIST_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        // Save Facebook session data
        editor.putString("facebookAccessToken", FacebookConnector.getInstance().getAccessToken());
        editor.putLong("facebookSessionExpires", FacebookConnector.getInstance().getSessionExpires());
        // Commit the edits
        editor.commit();
    }

    @Override
    public void onStop()
    {
        super.onStop();
        Log.d(TAG, "In the onStop() event");
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        Log.d(TAG, "In the onDestroy() event");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (requestCode)
        {
        case LOGIN_REQUEST:
            evaluateLoginResults(resultCode);
            break;
        default:
            // FIXME
            break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        // Load menu from resource
        getMenuInflater().inflate(R.menu.main_options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MenuChoice(item);
    }

    /**
     * Load saved internal application data
     */
    private void loadPersistentData()
    {
        SharedPreferences settings = getSharedPreferences(INTERNAL_PERSIST_NAME, Activity.MODE_PRIVATE);
        // Load Facebook session data
        FacebookConnector.getInstance().setSessionData(settings.getString("facebookAccessToken", null),
                settings.getLong("facebookSessionExpires", 0));
    }

    /**
     * Check logging result
     * 
     * @param resultCode
     *            result code returned by logging in activity
     */
    private void evaluateLoginResults(final int resultCode)
    {
        if (resultCode == LoggingActivity.RESULT_CANCELED)
        {
            finish();
        }
    }

    /**
     * Make proper action for selected menu option
     * 
     * @param item
     *            selected menu item
     * @return
     */
    private boolean MenuChoice(MenuItem item)
    {
        switch (item.getItemId())
        {
        case R.id.preferences_menu_item:
            startActivity(new Intent("android.intent.action.PREFERENCES"));
            return true;
        case R.id.about_menu_item:
            showAboutDialog();
            return true;
        case R.id.logout_menu_item:
            FacebookConnector.getInstance().logout(this,
                    runWorkingDialog(getString(R.string.logging_out), new DialogInterface.OnDismissListener()
                    {
                        @Override
                        public void onDismiss(DialogInterface dialog)
                        {
                            WMKAssistantActivity.this.startActivityForResult(
                                    new Intent("android.intent.action.LOGGING"), LOGIN_REQUEST);
                        }
                    }));
            return true;
        }

        return false;

    }

    /**
     * 'Working' dialog
     * 
     * Run working dialog with specified message (without title)
     * 
     * @param message
     *            message to display
     * @return started dialog
     */
    private ProgressDialog runWorkingDialog(String message)
    {
        return ProgressDialog.show(this, "", message, true);
    }

    /**
     * 'Working' dialog
     * 
     * Run working dialog with specified message (without title) and specified
     * action that should be run when the dialog closes
     * 
     * @param message
     *            message to display
     * @param dismissListener
     *            action to be started when the dialog closes
     * @return started dialog
     */
    private ProgressDialog runWorkingDialog(String message, DialogInterface.OnDismissListener dismissListener)
    {
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setTitle("");
        dialog.setMessage(message);
        dialog.setCancelable(false);
        dialog.setIndeterminate(true);
        dialog.setOnDismissListener(dismissListener);
        dialog.show();
        return dialog;
    }

    /**
     * Show about dialog
     */
    private void showAboutDialog()
    {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle(R.string.about);
        alertDialog.setMessage(getString(R.string.about_text));
        alertDialog.setButton(getString(R.string.ok_button), new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
            }
        });
        alertDialog.show();
    }
}